<?php

namespace App\Http\Controllers\admin_system;

use App\Common\Curl;
use App\Http\Controllers\Controller;
use App\Models\V1\LiveGiftListModels;
use App\Models\V1\LiveLinkManageModel;
use App\Models\V1\LiveModel;
use App\Models\V1\LiveMsgModel;
use App\Models\V1\MemberModel;
use App\Module\EntMemberDRP;
use App\Repository\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;

class LiveController extends Controller
{
    protected static $api;
    use Comment;

    private function utc_time($time)
    {
        date('Y-m-d\TH:i:s\Z', $time);
    }


    /**
     * 直播列表
     * */
    public function live_list(Request $request)
    {
        $liveModel = new LiveModel();
        $keywords  = $request->input('keywords');
        $lives     = $liveModel->get_lives($keywords);

        $data             = $this->live_stream_online_info();
        $oline_streamname = $data['OnlineInfo']['LiveStreamOnlineInfo'];

        foreach ($lives as $k => $v) {
            if (count($oline_streamname)) {
                foreach ($oline_streamname as $kk => $vv) {
                    if (md5($v->strem . '-laohou') === $vv['StreamName']) {
                        $v->live_online_status = '正在直播';
                    } elseif ($v->is_end === 1) {
                        $v->live_online_status = '直播已结束';
                    } elseif (strtotime($v->begin_time) < strtotime('now')) {
                        $v->live_online_status = '直播未关闭';
                    } else {
                        $v->live_online_status = $v->begin_time;
                    }
                }
            } else {
                if ($v->is_end === 1) {
                    $v->live_online_status = '直播已结束';
                } elseif (strtotime($v->begin_time) < strtotime('now')) {
                    $v->live_online_status = '直播未关闭';
                } else {
                    $v->live_online_status = $v->begin_time;
                }
            }
        }

        return view('admin_system/live/list', ['lives' => $lives, 'keywords' => $keywords]);
    }


    /**
     * 直播编辑
     *
     * */
    public function live_edit(Request $request)
    {
        return view('admin_system/live/edit');
    }

    //添加直播
    public function add_live(Request $request)
    {
        $face_img   = $request->file('face_img');
        $ad_img     = $request->file('ad_img');
        $face_img   = $this->upload_img($face_img);
        $ad_img     = $this->upload_img($ad_img);
        $begin_time = $request->input('begin_time');
        $input_time = strtotime($begin_time);
        $now_time   = strtotime('now');
        if ($input_time < $now_time) {//用户输入的时间过短

            return redirect()->back()->withInput()->with(['time_err' => '时间错误']);
        }


        $group_id = $this->create_chat_room($request->input('live_title'));
        $strem    = uniqid(mt_rand(100, 999));

        $live_model = LiveModel::create([
            'live_title'             => $request->input('live_title'),
            'chat_group_id'          => $group_id,
            'face_img'               => $face_img,
            'preview_video'          => ' ',
            'live_detail_view_times' => 0,
            'ali_live_view_times'    => 0,
            'viewed_times'           => 0,
            'begin_time'             => $request->input('begin_time'),
            'is_end'                 => 0,
            'description'            => $request->input('description'),
            'is_show_desc'           => 1,
            'ad_img'                 => $ad_img,
            'ad_text'                => $request->input('ad_text', ''),
            'is_show_ad'             => $request->input('is_show_ad', 0),
            'is_show'                => $request->input('is_show', 1),
            'notice'                 => $request->input('notice'),
            'live_type'              => $request->input('live_type'),
            'link_url'               => '',
            'push_msg'               => $request->input('push_msg', ''),
            'teacher_phone'          => '13761944771',
            'app'                    => 'laohoulundao',
            'strem'                  => $strem,
            'live_url'               => $this->create_live_room('laohoulundao', $strem),
            'live_status'            => 0,
            'is_completed'           => 0
        ]);

        //阿里直播鉴权
        $app      = $live_model->app;
        $strem    = md5($live_model->strem . '-laohou');
        $base_url = '/' . $app . '/' . $strem;

        $time       = strtotime($live_model->begin_time . '+3 hours');
        $hash_value = md5($base_url . '-' . $time . '-0-' . '0-' . 'shidao');
        $live_url   = $base_url . '?vhost=push.jdclo.com' . '&auth_key=' . $time . '-0-' . '0-' . $hash_value;
        $live_url   = 'rtmp://video-center.alivecdn.com' . $live_url;

        LiveModel::where('id', $live_model->id)->update(['live_url' => $live_url]);

        $params = [
            'Action'         => 'ForbidLiveStream',
            'DomainName'     => 'push.jdclo.com',
            'AppName'        => $live_model->app,
            'StreamName'     => md5($live_model->strem . '-laohou'),
            'LiveStreamType' => 'publisher'
        ];
        $url    = $this->live_url($params);
        $curl   = new Curl();
        $status = $curl->Get($url);

//        if ($live_model->is_end == 0 && $live_model->is_show == 1) {
//            $message = ['id' => 1, 'live_title' => $live_model->live_title, 'description' => $live_model->push_msg];
//            $data    = ['code' => 207, 'message' => $message];
//
//            $this->JpushContent($live_model->push_msg, '15210232041', $live_model->live_title, $data);
//        }


        return redirect()->action('admin_system\LiveController@add_link', ['type' => 1]);
    }


    /**
     * 创建聊天室
     * @param $name
     * @param $live_teacher
     * @return
     */
    public function create_chat_room($name)
    {
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/create_group?';
        $url = $this->InitTim($url);
//        $face_url = MemberModel::where(['DeleteMark' => 1, 'UserName' => $live_teacher])->pluck('FilePath1');
        $params = [
            'Owner_Account'   => '13761944771',
            'Type'            => 'AVChatRoom',
            'Name'            => substr($name, 0, 3),
            'ApplyJoinOption' => 'FreeAccess',
//            'FaceUrl'         => $face_url
        ];
        $data   = $this->curl_json($url, $params);

        $group_id = $data['GroupId'];

        return $group_id;
    }

    //编辑直播室
    public function edit_live_tim($group_id, $name, $introduction, $notification, array $faceurl)
    {
        $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $init   = $this->InitTim($url);
        $params = [
            "GroupId"         => $group_id,  // 要修改哪个群的基础资料（必填）
            "Name"            => $name,  // 群名称（选填）
            "Introduction"    => $introduction,  //  群简介（选填）
            "Notification"    => $notification,    // 群公告（选填）
            "FaceUrl"         => json_encode($faceurl),  // 群头像（选填）
            "MaxMemberNum"    => 500,  // 最大群成员数量（选填）
            "ShutUpAllMember" => "Off" //设置全员禁言（选填）:"On"开启，"Off"关闭
        ];

        $data = $this->curl_json($init, $params);
        dd($data);
    }

    //添加群主成员
    public function add_group_member($group_id, $member_account)
    {
        $url  = 'https://console.tim.qq.com/v4/group_open_http_svc/add_group_member?';
        $init = $this->InitTim($url);

        $params = [
            'GroupId'    => $group_id,
            'MemberList' => [
                ['Member_Account' => $member_account]
            ]
        ];

        $data = $this->curl_json($init, $params);

        dd($data);
    }

    //观看列表
    public function view_list($id)
    {
        $live     = LiveModel::where('id', $id)->first();
        $group_id = $live->chat_group_id;
        if ($live->is_end == 0) {
            $data     = $this->TimUsers($group_id);
            $userList = $data['MemberList'];
            $tmp      = [];
            foreach ($userList as $k => &$v) {
                $user_name                 = $v['Member_Account'];
                $user_info                 = MemberModel::where(['UserName' => $user_name, 'DeleteMark' => 1])
                    ->select('YourName as user_name', 'FilePath1 as avg', 'city')->first();
                $tmp[$k]['user_name']      = $user_info['user_name'];
                $tmp[$k]['avg']            = change_member_head_img($user_info['avg']);
                $tmp[$k]['role']           = $v['Role'];
                $tmp[$k]['join_time']      = $v['JoinTime'];
                $tmp[$k]['city']           = $this->region($user_info->city);
                $tmp[$k]['member_account'] = $v['Member_Account'];
                $tmp[$k]['is_limit']       = $this->is_limit_speak($user_name);
            }

            return view('admin_system.live.view', compact('tmp', 'group_id'));
        }

        return redirect()->back();
    }

    //获取地区
    public function region($id)
    {
        $tmp     = '';
        $regions = \DB::table('region')->where(['region_id' => $id])->select('region_name', 'parent_id')->first();

        $region = !is_null($regions) ? $regions->region_name : '未知';
        $tmp    .= $region . '-';
        if ($region != '未知' && $regions->parent_id != 0) {
            $regions = \DB::table('region')->where(['region_id' => $id])->select('region_name', 'parent_id')->first();
            $tmp     .= $regions->region_name;
            $this->region($regions->parent_id);
        } else {
            $tmp .= '中国';
        }

        return $tmp;
    }

    //获取聊天室所有的人
    public function TimUsers($group_id)
    {
//        $GroupId = $this->last_group_id($this->GroupId());
        $GroupId = $group_id;

        $url      = 'https://console.tim.qq.com/v4/group_open_http_svc/get_group_member_info?';
        $init     = $this->InitTim($url);
        $group_id = [
            'GroupId' => $GroupId
        ];

        $data = $this->curl_json($init, $group_id);

        return $data;
    }

    //是否设置或者取消为管理员
    public function setTimsAdmin(Request $request)
    {
        $member_account = $request->input('member_account');
        $role           = $request->input('role');
        $group_id       = $request->input('group_id');
        $url            = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_member_info?';
        $live_model     = LiveModel::where('chat_group_id', $group_id)->first();

        $init = $this->InitTim($url);
//        $GroupId = $this->last_group_id($this->GroupId());
        $GroupId = $group_id;

        $curl = new Curl();
        $role = $role === 'Admin' ? 'Member' : 'Admin';

        $params = [
            'GroupId'        => $GroupId,
            'Member_Account' => $member_account,
            'Role'           => $role,
        ];
        $data   = $curl->PostJson($init, json_encode($params));

        return redirect()->action('admin_system\LiveController@view_list', ['id' => $live_model->id]);

    }

    //Speak LIMIT
    public function speak_limit(Request $request)
    {
        $set_account = $request->input('set_account');
        $group_id    = $request->input('group_id');
        $live_model  = LiveModel::where('chat_group_id', $group_id)->first();
        $time        = 24;
        $url         = 'https://console.tim.qq.com/v4/openconfigsvr/setnospeaking?';
        $init        = $this->InitTim($url);

        $statue = $this->is_limit_speak($set_account);

        $params = [
            'Set_Account'            => $set_account,
            'GroupmsgNospeakingTime' => $time = $statue ? 0 : 3600//秒
        ];

        $curl = new Curl();
        $data = $curl->PostJson($init, json_encode($params));

        return redirect()->action('admin_system\LiveController@view_list', ['id' => $live_model->id]);
    }

    //用户是否被限制讲话
    public function is_limit_speak($get_account)
    {
        $url    = 'https://console.tim.qq.com/v4/openconfigsvr/getnospeaking?';
        $init   = $this->InitTim($url);
        $params = [
            'Get_Account' => $get_account
        ];
        $curl   = new Curl();
        $data   = json_decode($curl->PostJson($init, json_encode($params)), true);

        $statue = $data['GroupmsgNospeakingTime'] == 0 ? false : true;

        return $statue;
    }

    //初始格式api
    public function InitTim($url = '')
    {
        $live             = config('live');
        $sdkappid         = $live['SdkAppId'];
        $identifier       = $live['Identifier'];
        $private_pem_path = $live['PrivateKeyPath'];
        $signature        = $live['Signature'];
        $contenttype      = 'json';
        $random           = 9999999;

        $usersig = $this->signature($signature, $private_pem_path, $sdkappid, $identifier);

        $params = [
            'usersig'     => $usersig,
            'identifier'  => $identifier,
            'sdkappid'    => $sdkappid,
            'random'      => $random,
            'contenttype' => $contenttype
        ];
        $url    = $url . http_build_query($params);

        return $url;
    }

    //获取分组的ID
    public function GroupId()
    {
        $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/get_appid_group_list?';
        $url    = $this->InitTim($url);
        $curl   = new Curl();
        $params = [
            'Limit' => 1000,
            'Next'  => 0
        ];
        $data   = json_decode($curl->PostJson($url, json_encode($params)), true);

        $GroupId = $data['GroupIdList'];

        return $GroupId;
    }

    //获取最新的群主的ID
    public function last_group_id($group)
    {
        $length = count($group);

        return $group[$length - 1]['GroupId'];
    }

    //主讲发送信息
    public function sendMsg($msg, $group_id)
    {
        $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?';
        $init   = $this->InitTim($url);
        $url    = $init;
        $live   = config('live');
        $params = [
            'GroupId'      => $group_id,
            'From_Account' => $live['Identifier'],
            'Random'       => mt_rand(100, 999999),
            'MsgBody'      => [
                [
                    'MsgType'    => 'TIMTextElem',
                    'MsgContent' => [
                        'Text' => json_encode($msg)
                    ]
                ],

            ]
        ];
        $curl   = new Curl();
        $data   = $curl->PostJson($url, json_encode($params));

        return $data;
    }

    //直播的页面
    public function page()
    {
        return view('admin_system.live.page');
    }

    //签名
    public function signature($signature, $private_pem_path, $sdkappid, $identifier)
    {
        $file    = app_path('../zhengshu/tencent/sig');
        $command = $signature
            . ' ' . 'gen'
            . ' ' . escapeshellarg($private_pem_path)
            . ' ' . $file
            . ' ' . escapeshellarg($sdkappid)
            . ' ' . escapeshellarg($identifier);

        $ret = exec($command, $out, $status);
        if ($status == -1) {
            return null;
        }
        $sig = file_get_contents(app_path('../zhengshu/tencent/sig'));

        return $sig;
    }

    protected function curl_json($url, array $params)
    {
        $curl = new Curl();
        $data = $curl->PostJson($url, json_encode($params));

        return json_decode($data, true);
    }

    public function upload_img($file)
    {
        if ($file->isValid()) {
            $ext      = $file->getClientOriginalExtension();
            $new_file = date('Y-m-d-His') . '-' . uniqid() . '.' . $ext;
            $path     = public_path('admin/live/');
            $filePath = 'admin/live/' . $new_file;
            $file->move($path, $new_file);
        }

        return $filePath;
    }

    public function user_sig()
    {
        $live             = config('live');
        $signature        = $live['Signature'];
        $private_pem_path = $live['PrivateKeyPath'];
        $sdkappid         = $live['SdkAppId'];
        $identifier       = $live['Identifier'];

        return $this->signature($signature, $private_pem_path, $sdkappid, $identifier);
    }

    //主讲管理
    public function msg_view($id)
    {
        $group_id = implode('#', explode('-', $id));

        $student_msg = LiveMsgModel::where(['is_teacher' => 0, 'group_id' => $group_id])->orderBy('created_at', 'desc')->paginate(20);

        return view('admin_system.live.msg', compact('student_msg', 'group_id'));
    }

    public function send_msg(Request $request)
    {
        $group_id    = $request->input('group_id');
        $teacher_msg = LiveMsgModel::where(['is_teacher' => 1, 'group_id' => $group_id])->orderBy('created_at', 'desc')->get();

        return view('admin_system.live.send_msg', compact('teacher_msg', 'group_id'));
    }

    public function send_msg_data(Request $request)
    {
        $text     = $request->Input('msg');
        $img      = $request->file('img');
        $group_id = $request->Input('group_id');
        $width    = $request->input('width');
        $height   = $request->input('height');

        if (!$text && !$img) {
            return redirect()->back();
        }

        if ($text) {
            $msg = [
                'content' => $text,
                'type'    => 1,
                'width'   => '0',
                'height'  => '0'
            ];
        } else if ($img->isValid()) {
            $path = $this->upload_img($img);
            $msg  = [
                'content' => change_member_head_img('/' . $path),
                'type'    => 2,
                'width'   => $width,
                'height'  => $height
            ];
        }
        $status = $this->sendMsg($msg, $group_id);
        if ($status) {
            $teacher_msg = LiveMsgModel::where(['is_teacher' => 1, 'group_id' => $group_id])->orderBy('id', 'desc')->get();
            $group_id    = $request->input('group_id');

            return view('admin_system.live.send_msg', compact('teacher_msg', 'group_id'));
        }
    }

    public function edit_live($id)
    {
        $data   = LiveModel::where('id', $id)->first();
        $online = $this->live_stream_Online_user_num();
        LiveModel::where('id', $id)->update(['ali_live_view_times' => $online]);
        $liveLink      = LiveLinkManageModel::where(['live_id' => $id, 'link_type' => 1])->first();
        $live_url      = $this->html_live_url($id);
        $data->ad_link = $liveLink ? $liveLink->link : "";

        return view('admin_system.live.stop', compact('data', 'online', 'live_url'));
    }

    public function eidt_close(Request $request)
    {
        $id     = $request->input('id');
        $status = LiveModel::where('id', $id)->update(['is_end' => 1]);//关闭直播

        return redirect()->back();
    }

    public function push_live(Request $request)
    {
        $id = $request->input('id');
        $no = $request->input('no');

        $live = LiveModel::where('id', $id)->where(['is_end' => 0])->orderBy('id', 'desc')->first();
//        if (!$live) {
//            return redirect()->back()->with(['push_live' => '你还没有开启这个直播']);
//        }
        if (!$no) {
            $no = $live->push_msg;
        } else {
            LiveModel::where('id', $id)->update(['push_msg' => $no]);
        }
        $message = ['id' => (int)$id, 'live_title' => $live->live_title, 'description' => $no];
        $extra   = ['code' => 207, 'message' => json_encode($message)];


        $notice_people = $live->live_type == 1 ? $this->not_study() : $this->not_all();

        foreach ($notice_people as $k => $v) {
            $this->JpushContent($no, $v->UserName, $live->live_title, $extra);
        }

//        $this->JpushContent($no, '17192173329', $live->live_title, $extra);
//        $this->JpushContent($no, '18601723654', $live->live_title, $extra);
//        $this->JpushContent($no, '13761851830', $live->live_title, $extra);
//        $this->JpushContent($no, '18616333776', $live->live_title, $extra);
//        $this->JpushContent($no, '18501605383', $live->live_title, $extra);
//        $this->JpushContent($no, '15001979798', $live->live_title, $extra);
//        $this->JpushContent($no, '18917449601', $live->live_title, $extra);
//        $this->JpushContent($no, '18203594140', $live->live_title, $extra);
//        $this->JpushContent($no, '18203594140', $live->live_title, $extra);
//        $this->JpushContent($no, '15000606942', $live->live_title, $extra);
//        $this->JpushContent($no, '13167157753', $live->live_title, $extra);
//        $this->JpushContent($no, '15801761290', $live->live_title, $extra);
//        $this->JpushContent($no, '18739504996', $live->live_title, $extra);
//        $this->JpushContent($no, '17521136078', $live->live_title, $extra);
//        $this->JpushContent($no, '15001979798', $live->live_title, $extra);

        return redirect()->back();
    }

    public function change_live(Request $request)
    {
        $url  = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $url  = $this->InitTim($url);
        $id   = $request->input('id');
        $not  = $request->input('pusha');
        $st   = $request->input('sta');
        $live = LiveModel::where('id', $id)->where(['is_end' => 0])->orderBy('id', 'desc')->first();

        if (!$not) {
            $not = $live->notice;
        } else {
            LiveModel::where('id', $id)->update(['notice' => $not]);
        }
        $data = '{"is_notice":' . (int)$st . ',"notice":"' . $not . '"}';
        LiveModel::where('id', $id)->update(['is_notice' => $st]);
        $params = [
            'GroupId'      => $live->chat_group_id,
            'Notification' => $data
        ];
        $this->curl_json($url, $params);

        return redirect()->back();
    }

    //搜索
    public function serc(Request $request)
    {
        $hot      = $request->hot;
        $group_id = $request->input('group_id');
        $data     = $this->TimUsers($group_id);
        $userList = $data['MemberList'];
        $tmp      = [];
        foreach ($userList as $k => &$v) {
            $user_name                 = $v['Member_Account'];
            $user_info                 = MemberModel::where(['UserName' => $user_name, 'DeleteMark' => 1])
                ->select('YourName as user_name', 'FilePath1 as avg', 'city')->first();
            $tmp[$k]['user_name']      = $user_info['user_name'];
            $tmp[$k]['avg']            = change_member_head_img($user_info['avg']);
            $tmp[$k]['role']           = $v['Role'];
            $tmp[$k]['join_time']      = $v['JoinTime'];
            $tmp[$k]['city']           = $this->region($user_info->city);
            $tmp[$k]['member_account'] = $v['Member_Account'];
            $tmp[$k]['is_limit']       = $this->is_limit_speak($user_name);
        }
        $s_tmp = [];
        foreach ($tmp as $k => $v) {
            if ($v['user_name'] == $hot) {
                $s_tmp[$k][] = $v;
            } elseif ($v['member_account'] == $hot) {
                $s_tmp[$k][] = $v;
            }
        }
        $tmp = $s_tmp;
        $tmp = collect($tmp)->flatten(1)->toArray();

        return view('admin_system.live.view', compact('tmp', 'group_id'));
    }

    //修改群介绍
    public function intr(Request $request)
    {
        $id            = $request->input('id');
        $chat_group_id = $request->input('chat_group_id');
//        $link_url      = $request->input('link_url', '');
//        $show_time     = $request->input('show_time', 60);

        $link_url   = $request->input('ad_link');
        $ad_text    = $request->input('ad_text');
        $is_show_ad = $request->input('is_show_ad');
        $data       = LiveModel::where('id', $id)->first();
        if ($request->hasFile('ad_img')) {
            $file   = $request->file('ad_img');
            $ad_url = $this->upload_img($file);
        } else {
            $ad_url = $data->ad_img ?? '';
        }
        $ad_text = $ad_text ? $ad_text : $data->ad_text ?? '';
        $newAd   = [
            'ad_img'     => $ad_url,
            'ad_text'    => $ad_text,
            'is_show_ad' => $is_show_ad
        ];
        //更新直播信息
        LiveModel::where(['id' => $id])->update($newAd);
        //更新链接信息 link_type:1-订阅 2-分享
        LiveLinkManageModel::where(['live_id' => $id, 'link_type' => 1])->update(['link' => $link_url]);
        if ($is_show_ad == 1) {
            $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
            $url    = $this->InitTim($url);
            $data_p = [
                'title'      => $ad_text,
                'img_url'    => url($ad_url),
                'link_url'   => url($link_url->link ?? ''),
                'is_show_ad' => $is_show_ad
            ];
            $params = [
                'GroupId'      => $chat_group_id,
                'Introduction' => json_encode($data_p)
            ];
            $resp   = $this->curl_json($url, $params);
        } else {
            $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
            $url    = $this->InitTim($url);
            $data_p = [
                'title'      => $ad_text,
                'img_url'    => url($ad_url),
                'link_url'   => url($link_url->link ?? ''),
                'is_show_ad' => 0
            ];
            $params = [
                'GroupId'      => $chat_group_id,
                'Introduction' => json_encode($data_p)
            ];
            $resp   = $this->curl_json($url, $params);
        }

        return redirect()->back();
        //$live_url = $this->html_live_url($id);
        //return view('admin_system.live.stop', compact('data', 'live_url'));
    }

    //修改群观看次数
    public function view_times(Request $request)
    {
        $id            = $request->input('id');
        $viewed_times  = $request->input('viewed_times');
        $chat_group_id = $request->input('chat_group_id');

        LiveModel::where(['id' => $id])->increment('add_view_times', $viewed_times);
        $url                    = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $url                    = $this->InitTim($url);
        $live_model             = LiveModel::where('id', $id)->orderBy('id', 'desc')->first();
        $live_detail_view_times = $live_model->viewed_times;
        $add_view_times         = $live_model->add_view_times;

        $view_times = $add_view_times + $live_detail_view_times;
        LiveModel::where('id', $id)->update(['viewed_times' => $view_times]);

        $params = [
            'GroupId' => $chat_group_id,
            'Name'    => (string)$view_times
        ];
        $status = $this->curl_json($url, $params);

        return redirect()->back();
    }

    //随机增加观看的人数
    public function rand_views($id, $chat_group_id)
    {
        $live = LiveModel::where(['id' => $id])->first();
        if ($live->is_show == 1 && $live->is_end == 0) {
            $rand = mt_rand(100, 200);
            sleep(20);
            $viewed_times = ceil($rand);
            LiveModel::where(['id' => $id])->update(['viewed_times' => $viewed_times]);
            $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
            $url    = $this->InitTim($url);
            $params = [
                'GroupId' => $chat_group_id,
                'Name'    => $viewed_times
            ];
            $this->curl_json($url, $params);
            $this->rand_views($id, $chat_group_id);
        }
    }

    //是否发布直播
    public function send_live(Request $request)
    {
        $sta = $request->input('is_show');
        $id  = $request->input('id');
        LiveModel::where('id', $id)->update(['is_show' => $sta]);
        $data = LiveModel::where('id', $id)->first();

        $live_url = $this->html_live_url($id);


        return view('admin_system.live.stop', compact('data', 'live_url'));
    }

    //通知学习官
    public function not_study()
    {
        $user_names = EntMemberDRP::where(['DRPLevel' => 1, 'memberdrp.DeleteMark' => 1])->leftJoin('memberinfo as m', 'm.MemNumber', '=', 'memberdrp.MemNumber')
            ->where(['m.DeleteMark' => 1])->select('UserName')->get();

        return $user_names;
    }

    //推送所有人
    public function not_all()
    {
        $user_names = MemberModel::where(['DeleteMark' => 1])->select('UserName')->get();

        return $user_names;
    }

    public function live_user()
    {
        $data = \DB::table('member_online_log')->orderBy('begin_time', 'desc')->get();

    }

    //阿里云创建直播房间
    public function create_live_room($app, $strem)
    {
        $config = config('live');
        $strem  = md5($strem . '-laohou');

        $end_url  = '/' . $app . '/' . $strem . '?vhost=push.jdclo.com';
        $base_url = $config['base_url'];
        $live_url = $base_url . $end_url;

        return $live_url;
    }

    //直播api公共的参数
    public function live_common_params()
    {
        date_default_timezone_set('UTC');
        $access_id = config('live')['access_id'];
        $params    = [
            'Format'           => 'JSON',
            'Version'          => '2016-11-01',
            'AccessKeyId'      => $access_id,
            'SignatureMethod'  => 'HMAC-SHA1',
            'Timestamp'        => date('Y-m-d\TH:i:s\Z', time()),//'2017-12-28T14:30:00Z',
            'SignatureVersion' => '1.0',
            'SignatureNonce'   => mt_rand()
        ];

        return $params;
    }

    //直播签名
    public function live_sigin($method, $url)
    {
        $string_to_sign = $method . "&" . urlencode("/") . "&" . urlencode($url);

        return $string_to_sign;
    }

    //直播url---
    public function live_url($params)
    {
        $start  = $this->live_common_params();
        $params = array_merge($params, $start);
        ksort($params);
        $url = http_build_query($params);
        $str = $this->live_sigin('GET', $url);

        $accesskey = config('live')['accesskey'] . "&";

        $str  = hash_hmac('sha1', $str, $accesskey, true);
        $sign = base64_encode($str);

        $params = array_merge($params, ['Signature' => $sign]);

        $com_query = http_build_query($params);
        $url       = 'https://live.aliyuncs.com?' . $com_query . '';

        return $url;
    }


    public function live_strem()
    {
        $live   = LiveModel::where('is_end', 0)->orderBy('id', 'desc')->first();
        $params = [
            'Action'         => 'DescribeLiveStreamsPublishList',
            'DomainName'     => 'push.jdclo.com',
            'LiveStreamType' => 'publisher',
            'AppName'        => $live->app,
            'StreamName'     => $live->strem,
            'StartTime'      => '2017-12-1T19:00:00Z',
            'EndTime'        => '2017-12-30T19:00:00Z'
        ];
        $url    = $this->live_url($params);
        $curl   = new Curl();
        $data   = $curl->Get($url);
        dd($data);

    }

    public function all_callback(Request $request)
    {
//        Cache::set('aaa', json_encode($request->all()));
        debug_log('ok', json_encode($request->all()));
//        cache('live_status', 'ok la');
        cache(['live_status' => json_encode($request->all())], 5);
    }

    public function get_ali()
    {
        dump(cache('live_status'));
    }

    //关闭直播间
    public function close_live($id, $type)
    {
        $live       = LiveModel::where('id', $id)->first();
        $close_live = $type;
        $params     = [
            'Action'         => 'ForbidLiveStream',
            'DomainName'     => 'push.jdclo.com',
            'AppName'        => $live->app,
            'StreamName'     => md5($live->strem . '-laohou'),
            'LiveStreamType' => 'publisher'
        ];
        $url        = $this->live_url($params);
        $curl       = new Curl();
        $status     = $curl->Get($url);
        if ($status) {
            $chat_group_id = $live->chat_group_id;

            $this->send_face_url_notice($chat_group_id, $close_live);
        }

        if ($close_live == 3) {//停止直播
            LiveModel::where('id', $id)->update(['is_end' => 1, 'live_status' => 3]);
        } elseif ($close_live == 2) {//暂停直播
            LiveModel::where('id', $id)->update(['live_status' => 2]);
        } elseif ($close_live == 4) {//即将开始
            LiveModel::where('id', $id)->update(['live_status' => 4]);
        }

        return redirect()->back();
    }

    //开启直播间
    public function open_live($id, $type)
    {
        $live      = LiveModel::where('id', $id)->first();
        $open_live = $type;
        $params    = [
            'Action'         => 'ResumeLiveStream',
            'DomainName'     => 'push.jdclo.com',
            'AppName'        => $live->app,
            'StreamName'     => md5($live->strem . '-laohou'),
            'LiveStreamType' => 'publisher'
        ];
        $url       = $this->live_url($params);
        $curl      = new Curl();
        $status    = $curl->Get($url);

        if ($status) {
            $chat_group_id = $live->chat_group_id;
            $this->send_face_url_notice($chat_group_id, $open_live);
        }
        LiveModel::where('id', $id)->update(['live_status' => 1, 'is_end' => 0]);//开启直播


        return redirect()->back();
    }

    public function DescribeLiveStreamsPublishList()
    {
        $live   = LiveModel::where(['is_end' => 0])->orderBy('id', 'desc')->first();
        $params = [
            'Action'     => 'DescribeLiveStreamsPublishList',
            'DomainName' => 'push.jdclo.com',
            'AppName'    => $live->app,
            'StreamName' => $live->strem,
            'StartTime'  => '2017-12-01T19:00:00Z',
            'EndTime'    => '2017-12-29T19:00:00Z',
        ];
        $url    = $this->live_url($params);
        $curl   = new Curl();
        $status = $curl->Get($url);
        dd($status);
    }

    public function live_stream_Online_user_num()
    {
        $live = LiveModel::orderBy('id', 'desc')->first();

        $params = [
            'Action'     => 'DescribeLiveStreamOnlineUserNum',
            'DomainName' => 'push.jdclo.com',
            'AppName'    => $live->app,
            'StreamName' => md5($live->strem . '-laohou')
        ];

        $url  = $this->live_url($params);
        $curl = new Curl();
        $data = json_decode($curl->Get($url), true);

        return $data['OnlineUserInfo']['LiveStreamOnlineUserNumInfo'][0]['UserNumber'];
    }

    //发送直播tim通知
    public function send_face_url_notice($group_id, $type)
    {
        $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $url    = $this->InitTim($url);
        $params = [
            'GroupId' => $group_id,
            'FaceUrl' => $type
        ];
        $res    = $this->curl_json($url, $params);

        return $res;
    }

    //查询推流在线的列表
    public function live_stream_online_info()
    {

        $params = [
            'Action'     => 'DescribeLiveStreamsOnlineList',
            'DomainName' => 'push.jdclo.com',
            'AppName'    => ''
        ];
        $url    = $this->live_url($params);
        $curl   = new Curl();
        $data   = $curl->Get($url);

        return json_decode($data, true);
    }

    //Html直播
    public function html_live_url($id)
    {
        $live_model = LiveModel::where('id', $id)->first();
        $app        = $live_model->app;
        $strem      = md5($live_model->strem . '-laohou');
        $base_url   = '/' . $app . '/' . $strem;

        $time = strtotime($live_model->begin_time . '+3 hours');

        $hash_value = md5($base_url . '-' . $time . '-0-' . '0-' . 'shidao');
        $live_url   = 'rtmp://push.jdclo.com' . $base_url . '?auth_key=' . $time . '-0-' . '0-' . $hash_value;

        return $live_url;
    }

    //连接管理
    public function link_manage()
    {
        //1.获取所有的订阅的内容
        $dingyue = LiveLinkManageModel::where(['link_type' => 1])
            ->leftjoin('live as l', 'l.id', '=', 'live_link_manage.live_id')
            ->select('live_link_manage.id', 'live_link_manage.link_type', 'live_link_manage.live_id', 'l.ad_text', 'l.live_title', 'l.description')->orderBy('id', 'desc')
            ->get();
        $share   = LiveLinkManageModel::where(['link_type' => 2])->orderBy('id', 'desc')->get();

        return view('admin_system.live.link_manage', compact('dingyue', 'share'));
    }

    public function add_link($type)
    {
        $live = LiveModel::orderBy('id', 'desc')->get();

        return view('admin_system.live.add_link', compact('type', 'live'));
    }

    //保存连接
    public function save_link(Request $request)
    {

        $file = $request->file('share_img');

        $share_img = $file ? $this->upload_img($file) : '';

        $content     = $request->input('conten');
        $live_id     = $request->input('live_id');
        $title       = $request->input('live_title');
        $description = $request->input('description');
        $link_type   = $request->input('link_type');

        $status = LiveLinkManageModel::where(['live_id' => $live_id, 'link_type' => $link_type])->first();
        if ($status) {
            return redirect()->back();
        }

        $link = "/admin_system/live/link/" . $link_type . "/" . $live_id . "";

        $res = LiveLinkManageModel::create(compact('content', 'share_img', 'live_id', 'link', 'title', 'description', 'link_type'));

        $count = LiveLinkManageModel::where('live_id', $live_id)->get();
        if (count($count) >= 2) {
            LiveModel::where('id', $live_id)->update(['is_completed' => 1]);

            return response()->json(['is_completed' => 1]);
        } else {
            return response()->json(['is_completed' => 0]);
        }

//        return redirect()->action('admin_system\LiveController@add_link', ['type' => 2]);
//        return redirect()->action('admin_system\LiveController@link_manage');
    }

    //显示分享的连接
    public function show_link($type, $live_id)
    {
        $content = LiveLinkManageModel::where(['live_id' => $live_id, 'link_type' => $type])
            ->orderBy('id', 'desc')
            ->select('content')->first();

        return view('admin_system.live.show_link', compact('content'));
    }

    //消息撤回
    public function group_msg_recall()
    {
        $url    = 'https://console.tim.qq.com/v4/group_open_http_svc/group_msg_recall?';
        $url    = $this->InitTim($url);
        $params = "{
            'GroupId': '@TGS#aGZNJ5AFF',
            'MsgSeqList':[
                    'MsgSeq':19,
                ]
            }";

        $list   = [
            'MsgSeq' => 19
        ];
        $params = [
            'GroupId'    => '@TGS#aGZNJ5AFF',
            'MsgSeqList' => [$list]
        ];

        $curl = new Curl();
        $data = $curl->PostJson($url, json_encode($params));

        dd($data);
    }

    //编辑器图片保存管理
    public function live_editor_img(Request $request)
    {
        $file = $request->file('editor_img');
        $url  = $this->upload_img($file);
        $res  = [
            'errno' => 0,
            'data'  => [
                url($url)
            ]
        ];

        return response()->json($res);
    }

    //礼物管理
    public function live_gift_manage()
    {
        $gift = LiveGiftListModels::get();

        return view('admin_system.live.live_gift_manage', compact('gift'));
    }

    //礼物添加
    public function live_gift_add()
    {
        return view('admin_system.live.add_live_gift');
    }

    //礼物保存
    public function live_gift_save(Request $request)
    {
        $name    = $request->input('name');
        $price   = $request->input('price');
        $file    = $request->file('img_url');
        $img_url = $this->upload_img($file);
        $data    = compact('name', 'price', 'img_url');
        $res     = LiveGiftListModels::create($data);
        dd($res);
    }

    //删除礼物
    public function del_gift($id)
    {
        $res = LiveGiftListModels::destroy($id);

        return redirect()->back();
    }

    //编辑礼物
    public function edit_gift($id)
    {
        $gift = LiveGiftListModels::find($id);

        return view('admin_system.live.edit_gift', compact('gift'));
    }

    public function edit_gift_save(Request $request)
    {
        $name  = $request->input('name');
        $price = $request->input('price');
        $file  = $request->file('img_url');
        $id    = $request->input('id');
        if ($file) {
            $img_url = $this->upload_img($file);
        }
        $buter = $this->upw($name, $price, $img_url ?? false);
        $res   = LiveGiftListModels::where('id', $id)->update($buter);

        return redirect()->back();
    }

    public function upw($name, $price, $img_url)
    {
        $data = $img_url ? ['name' => $name, 'price' => $price, 'img_url' => $img_url] : ['name' => $name, 'price' => $price];

        return $data;
    }

    //系统通知
    public function send_group_system_notification($note)
    {
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification?';
        $url = $this->InitTim($url);

        $live = LiveModel::where(['is_show' => 1, 'is_end' => 0])->orderBy('id', 'desc')->first();

        $params = [
            'GroupId' => $live->chat_group_id,
            'Content' => json_encode($note)
        ];
        $res    = $this->curl_json($url, $params);

        return $res;
    }

    public function modify_add_er()
    {
        $base_url = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $url      = $this->InitTim($base_url);
        $params   = [
            "GroupId"        => '@TGS#aQQVVDBFL',
            "AppDefinedData" => [
                [
                    "Key"   => "live_msg",
                    "Value" => '666666'
                ]
            ]
        ];
        $res      = $this->curl_json($url, $params);
        dd($res);
    }

    //直播连接编辑
    public function live_link_edit($type, $id)
    {

        $link = LiveLinkManageModel::where(['id' => $id, 'link_type' => $type])->orderBy('id', 'desc')->first();

        $title = $type == 1 ? LiveModel::where('id', $link->live_id)->select('live_title')->first() : '';

        return view('admin_system.live.link_manage_edit', compact('link', 'title', 'type'));
    }

    public function live_link_edit_add(Request $request)
    {
        $file = $request->file('share_img');

        $share_img = $file ? $this->upload_img($file) : '';

        $content = $request->input('conten');


        $live_id     = $request->input('live_id');
        $title       = $request->input('live_title');
        $description = $request->input('description');
        $link_type   = $request->input('link_type');
        $link_id     = $request->input('link_id');


        $share_img = !$share_img && $link_type == 2 ? LiveLinkManageModel::where('id', $link_id)->select('share_img')->first()->share_img : $share_img;

        $link = "/admin_system/live/link/" . $link_type . "/" . $live_id . "";
        $res  = LiveLinkManageModel::where('id', $link_id)->orderBy('id', 'desc')->update(compact('content', 'share_img', 'live_id', 'link', 'title', 'description', 'link_type'));

        return redirect()->action('admin_system\LiveController@link_manage');
    }

    public function live_link_del($id)
    {
        dd($id);
        LiveLinkManageModel::destroy($id);

        return redirect()->back();
    }

    public function show_live($id, $type)
    {
        $res = LiveModel::where('id', $id)->update(['is_show' => $type]);

        return redirect()->back();
    }

    public function input_word()
    {
        $word = '内幕 侵犯 骗子 穷疯了 不要脸 垃圾 陷阱 诅咒 霸王条款 破 公道 阴谋 漏洞 骚扰 争议 强盗 强抢 罪 无耻 坑人 坑爹 惹的祸 惹 祸 无语 打人 不能信 强制 停卡 被骗 怀疑 诈骗 疑似 真是拽 强迫 投诉 有待深思 诚信度 骗人 牛逼 大便 一坨 无奈 无言 垄断 欺压 黑幕 背后 神秘 神密 老是这样 收费不明 擅自 自毁长城 自毁 悲哀 太黑 屏蔽 太差 丑恶嘴脸  爬你吗的 武装 不过如此 忽悠 他妈的 自杀 私募 黑马 卑鄙 伎俩 投诉 揭露 销魂 霸占 无情 封杀 纠结 头痛 失望 愤怒 真假 无良 痛 尊重 擅自 迷恋 传说 悲惨 遭遇 杯具 水准 鄙视 下套子 差钱 坑钱 耻辱 肆意 声讨 良心 不相信 蒙人 威胁 顺手牵羊 法庭 承诺 不满 强烈 一塌糊涂 死 谨防 坑害 大爷的 强悍 注意 受害 潜规则 缺斤少两 虐待 倒闭 天理难容 无能 无赖 控诉 篡改 绑架 骚扰 拖欠 公平 曝光 告发 小心 上当 内幕 揭秘 狗屎 揭穿 骗局 谴责';
        $word = explode(' ', $word);

        return $word;
    }

    //脏字管理
    public function dirty_words_list_add()
    {
        $base_url = 'https://console.tim.qq.com/v4/openim_dirty_words/add?';
        $url      = $this->InitTim($base_url);

        $params = [
            "DirtyWordsList" => $this->input_word()
        ];
        $res    = $this->curl_json($url, $params);
        dd($res);
    }

    public function dirty_words_list_get()
    {
        $base_url = 'https://console.tim.qq.com/v4/openim_dirty_words/get?';
        $url      = $this->InitTim($base_url);
        $res      = $this->curl_json($url, []);

        dd($res);
    }
}















